// DiagnosisServiceImpl.java
package com.projects.modular.realty.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.projects.modular.realty.entity.AssessmentDetail;
import com.projects.modular.realty.entity.Child;
import com.projects.modular.realty.entity.Diagnosis;
import com.projects.modular.realty.entity.RegisteredUsers;
import com.projects.modular.realty.mapper.DiagnosisMapper;
import com.projects.modular.realty.model.params.AssessmentDetailParam;
import com.projects.modular.realty.model.params.DiagnosisParam;
import com.projects.modular.realty.model.vo.DiagnosisQueryVo;
import com.projects.modular.realty.model.vo.DiagnosisVo;
import com.projects.modular.realty.service.AssessmentDetailService;
import com.projects.modular.realty.service.ChildService;
import com.projects.modular.realty.service.DiagnosisService;
import com.projects.modular.realty.service.RegisteredUsersService;
import com.projects.modular.system.entity.Task;
import com.projects.modular.system.service.TaskService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 疼痛记录服务实现类
 *
 * @author 曾大顺
 * @since 2025-02-11
 */
@Service
public class DiagnosisServiceImpl extends ServiceImpl<DiagnosisMapper, Diagnosis> implements DiagnosisService {

    @Resource
    private AssessmentDetailService assessmentDetailService;

    @Resource
    private DiagnosisMapper diagnosisMapper;

    @Resource
    private ChildService childService;

    @Resource
    private RegisteredUsersService registeredUsersService;

    @Resource
    private TaskService taskService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(DiagnosisParam diagnosisParam) {
        Diagnosis diagnosis = new Diagnosis();
        BeanUtils.copyProperties(diagnosisParam, diagnosis);
        diagnosis.setPainPart(JSONObject.toJSONString(diagnosisParam.getPainPart()));
        diagnosis.setCreateTime(LocalDateTime.now());
        this.save(diagnosis);

        // 添加评估详情
        List<AssessmentDetailParam> assessmentDetailList = diagnosisParam.getAssessmentDetailList();
        for (AssessmentDetailParam assessmentDetailParam : assessmentDetailList) {
            assessmentDetailParam.setDiagnosisId(diagnosis.getDiagnosisId());
            this.assessmentDetailService.add(assessmentDetailParam);
        }

        // 如果疼痛等级不是0级,就根据订阅状态添加定时任务
        if (!"0".equals(diagnosis.getPainLevel())) {
            // 通过孩子id获取用户信息
            Child child = childService.getById(diagnosis.getChildId());
            RegisteredUsers user = registeredUsersService.getById(child.getUserId());
            if (user.getSubscribeStatus() == 1 && user.getOpenId() != null) {
                Task task = new Task();
                task.setUserName(user.getUserName());
                task.setOpenId(user.getOpenId());
                task.setCreateTime(new Date());
                switch (diagnosis.getPainLevel()) {
                    case "2":
                        // 重度疼痛2分(q1d)，干预后再次评估
                        task.setSendTime(DateUtils.addHours(new Date(), 24));
                        break;
                    case "4":
                    case "6":
                        // 重度疼痛4-6分(q8h)，干预后再次评估
                        task.setSendTime(DateUtils.addHours(new Date(), 8));
                        break;
                    case "8":
                    case "10":
                        // 重度疼痛8-10分(q1h)，干预后再次评估
                        task.setSendTime(DateUtils.addHours(new Date(), 1));
                        break;
                    default:
                        break;
                }
                taskService.save(task);

            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String diagnosisId) {
        this.removeById(diagnosisId);
        // 删除评估详情
        this.assessmentDetailService.deleteByDiagnosisId(diagnosisId);
    }

    @Override
    public void update(DiagnosisParam diagnosisParam) {
        Diagnosis diagnosis = new Diagnosis();
        BeanUtils.copyProperties(diagnosisParam, diagnosis);
        this.updateById(diagnosis);
    }

    @Override
    public DiagnosisParam getDetailById(String diagnosisId) {
        Diagnosis diagnosis = this.getById(diagnosisId);
        return getDiagnosisParam(diagnosis);

    }

    @Override
    public List<DiagnosisParam> getByChildId(String childId) {
        QueryWrapper<Diagnosis> wrapper = new QueryWrapper<>();
        // 根据时间倒序排序
        wrapper.lambda().eq(Diagnosis::getChildId, childId).orderByDesc(Diagnosis::getCreateTime);
        List<Diagnosis> diagnoses = this.baseMapper.selectList(wrapper);
        List<DiagnosisParam> diagnosisParamList = new ArrayList<>();
        for (Diagnosis diagnosis : diagnoses) {
            DiagnosisParam diagnosisParam = getDiagnosisParam(diagnosis);
            diagnosisParamList.add(diagnosisParam);
        }
        return diagnosisParamList;
    }

    @Override
    public List<DiagnosisParam> getDiagnosisList(DiagnosisVo diagnosisVo) {
        DiagnosisQueryVo diagnosisQueryVo = new DiagnosisQueryVo();
        diagnosisQueryVo.setChildId(diagnosisVo.getChildId());
        // 角色
        diagnosisQueryVo.setRole(diagnosisVo.getRole());
        // 疼痛部位
        diagnosisQueryVo.setPainPart(diagnosisVo.getPainPart());
        // 时间范围查询
        if (!StringUtils.isEmpty(diagnosisVo.getDateRange())) {
            switch (diagnosisVo.getDateRange()) {
                case "一周内":
                    diagnosisQueryVo.setDateStart(LocalDateTime.now().minusDays(7).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    break;
                case "一个月内":
                    diagnosisQueryVo.setDateStart(LocalDateTime.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    break;
                case "三个月内":
                    diagnosisQueryVo.setDateStart(LocalDateTime.now().minusMonths(3).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    break;
                default:
            }
        }
        // 疼痛级别查询
        if (!StringUtils.isEmpty(diagnosisVo.getPainLevel())) {
            switch (diagnosisVo.getPainLevel()) {
                case "轻度":
                    diagnosisQueryVo.setPainLevel(Collections.singletonList("2"));
                    break;
                case "中度":
                    diagnosisQueryVo.setPainLevel(Arrays.asList("4", "6"));
                    break;
                case "重度":
                    diagnosisQueryVo.setPainLevel(Arrays.asList("8", "10"));
                    break;
                default:
                    break;
            }
        }
        List<Diagnosis> diagnosisList = diagnosisMapper.getDiagnosisList(diagnosisQueryVo);
        if (CollectionUtils.isEmpty(diagnosisList)) {
            return new ArrayList<>();
        }
        List<DiagnosisParam> diagnosisParamList = new ArrayList<>();
        for (Diagnosis diagnosis : diagnosisList) {
            DiagnosisParam diagnosisParam = getDiagnosisParam(diagnosis);
            diagnosisParamList.add(diagnosisParam);
        }
        return diagnosisParamList;
    }

    /**
     * 获取疼痛详情
     *
     * @param diagnosis
     * @return
     */
    private DiagnosisParam getDiagnosisParam(Diagnosis diagnosis) {
        DiagnosisParam diagnosisParam = new DiagnosisParam();
        BeanUtils.copyProperties(diagnosis, diagnosisParam);
        diagnosisParam.setPainPart(JSONObject.parseObject(diagnosis.getPainPart(), JSONObject.class));
        // 查询疼痛详情
        QueryWrapper<AssessmentDetail> assessmentWrapper = new QueryWrapper<>();
        assessmentWrapper.lambda().eq(AssessmentDetail::getDiagnosisId, diagnosis.getDiagnosisId());
        List<AssessmentDetail> assessmentDetailList = this.assessmentDetailService.list(assessmentWrapper);
        List<AssessmentDetailParam> assessmentDetailParamList = new ArrayList<>();
        for (AssessmentDetail assessmentDetail : assessmentDetailList) {
            AssessmentDetailParam assessmentDetailParam = new AssessmentDetailParam();
            BeanUtils.copyProperties(assessmentDetail, assessmentDetailParam);
            JSONObject content = JSONObject.parseObject(assessmentDetail.getContent(), JSONObject.class);
            assessmentDetailParam.setContent(content);
            assessmentDetailParamList.add(assessmentDetailParam);
        }
        diagnosisParam.setAssessmentDetailList(assessmentDetailParamList);
        return diagnosisParam;
    }


}
